//
//  CBMicphoneViewController.m
//  KangaRoos
//
//  Created by Harvey on 2017/10/5.
//  Copyright © 2017年 Haley. All rights reserved.
//

#import "CBMicphoneViewController.h"
#import "CBBarAnimationView.h"
#import "BluetoothManager.h"
#import "NSString+QCExtension.h"

#import "EZAudio.h"

#import <AVFoundation/AVFoundation.h>

@interface CBMicphoneViewController ()<EZMicrophoneDelegate>

@property (nonatomic, strong) EZMicrophone *microphone;

@property (strong, nonatomic) CBBarAnimationView            *barAnimationView;

@property (strong, nonatomic) UIButton            *startBtn;
@property (strong, nonatomic) UIButton            *stopBtn;

@property (nonatomic, strong) NSMutableArray *frequencyArray;

@end

@implementation CBMicphoneViewController

#pragma mark - life circle method
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = showText(@"麦克风律动");
    
    [self initSubViews];
    
    [self initAudioSetting];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    //关闭远程事件
    [[UIApplication sharedApplication] endReceivingRemoteControlEvents];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [self stopRecord];
    
    AVAudioSession *session = [AVAudioSession sharedInstance];
    NSError *error;
    [session setCategory:AVAudioSessionCategoryPlayback error:&error];
    if (error) {
        NSLog(@"Error setting up audio session category: %@", error.localizedDescription);
    }
    [session setActive:YES error:&error];
    if (error) {
        NSLog(@"Error setting up audio session active: %@", error.localizedDescription);
    }
}

#pragma mark - setter & getter
- (NSMutableArray *)frequencyArray
{
    if (!_frequencyArray) {
        _frequencyArray = [NSMutableArray array];
    }
    return _frequencyArray;
}

#pragma mark - private method
- (void)initAudioSetting
{
    self.microphone = [EZMicrophone microphoneWithDelegate:self];
    
    AVAudioSession *session = [AVAudioSession sharedInstance];
    NSError *error;
    [session setCategory:AVAudioSessionCategoryPlayAndRecord error:&error];
    if (error) {
        NSLog(@"Error setting up audio session category: %@", error.localizedDescription);
    }
    [session setActive:YES error:&error];
    if (error) {
        NSLog(@"Error setting up audio session active: %@", error.localizedDescription);
    }
    
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
    if (authStatus == AVAuthorizationStatusDenied || authStatus == AVAuthorizationStatusRestricted) {
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:nil message:showText(@"请去【设置】---> 【隐私】---> 【麦克风】为该应用打开权限，否则无法采集声音") preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:showText(@"确定") style:UIAlertActionStyleCancel handler:nil];
        [alertVC addAction:cancelAction];
        [self presentViewController:alertVC animated:YES completion:nil];
    }
}

- (void)initSubViews
{
    CGFloat paddingH = 60;
    CGFloat remainH = kHeight - 64-(kWidth-120)-80;
    if (remainH < paddingH * 3) {
        paddingH = remainH / 3;
    }
    
    CGFloat topW = kWidth-120;
    UIImageView *topImageView = [[UIImageView alloc] initWithFrame:CGRectMake(60, paddingH, topW, topW)];
    topImageView.image = [UIImage imageNamed:@"mic_bg"];
    [self.view addSubview:topImageView];
    
    CGFloat barW = topW * 0.7;
    self.barAnimationView = [[CBBarAnimationView alloc] initWithFrame:CGRectMake(0, 0, barW, barW)];
    self.barAnimationView.center = CGPointMake(topW*0.5, topW*0.5);
    self.barAnimationView.backgroundColor = [UIColor clearColor];
    [topImageView addSubview:self.barAnimationView];
    
    UIButton *startBtn = [[UIButton alloc] initWithFrame:CGRectMake((kWidth-80)*0.5, kHeight-64-80-paddingH, 80, 80)];
    [startBtn setBackgroundImage:[UIImage imageNamed:@"mic_bg"] forState:UIControlStateNormal];
    [startBtn setTitle:showText(@"开始") forState:UIControlStateNormal];
    startBtn.titleLabel.font = [UIFont systemFontOfSize:14.0f];
    [startBtn addTarget:self action:@selector(startRecord) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:startBtn];
    self.startBtn = startBtn;
    
    UIButton *stopBtn = [[UIButton alloc] initWithFrame:CGRectMake((kWidth-80)*0.5, kHeight-64-80-paddingH, 80, 80)];
    [stopBtn setBackgroundImage:[UIImage imageNamed:@"mic_bg"] forState:UIControlStateNormal];
    [stopBtn setTitle:showText(@"停止") forState:UIControlStateNormal];
    stopBtn.titleLabel.font = [UIFont systemFontOfSize:14.0f];
    [stopBtn addTarget:self action:@selector(stopRecord) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:stopBtn];
    self.stopBtn = stopBtn;
    self.stopBtn.hidden = YES;
}

- (void)addFrequencyData:(float)frequencyData
{
    //    NSLog(@"RMS:%f",frequencyData);
    self.barAnimationView.scale = frequencyData * 10000;
    // 假设0.15相当于16,则
    int value = (int)(frequencyData / 0.15 * 16);
    if (value > 16) {
        value = 16;
    }
    NSNumber *number = @(value);
    [self.frequencyArray addObject:number];
    if (self.frequencyArray.count >= 8) {
        NSString *hexString = @"";
        for (int j = 0; j < 8; j++) {
            hexString = [hexString stringByAppendingFormat:@"%02x",[self.frequencyArray[j] intValue]];
        }
        BOOL isRhythm = [[NSUserDefaults standardUserDefaults] boolForKey:kRhythmMode];
        
        if (isRhythm) {
            NSString *data = [NSString stringWithFormat:@"01%@",hexString];
            NSString *lengthData = [NSString stringWithFormat:@"0009%@",data];
            NSString *finalData = [NSString finalDataWith:lengthData];
            [[BluetoothManager standardManager] writCommad:finalData];
        }
        [self.frequencyArray removeAllObjects];
    }
}

- (void)   microphone:(EZMicrophone *)microphone
     hasAudioReceived:(float **)buffer
       withBufferSize:(UInt32)bufferSize
 withNumberOfChannels:(UInt32)numberOfChannels
{
    __weak typeof (self) weakSelf = self;
    dispatch_async(dispatch_get_main_queue(), ^{
        for (int i = 0; i < numberOfChannels; i++) {
            float freData = [EZAudioUtilities RMS:buffer[i] length:bufferSize];
            [weakSelf addFrequencyData:freData];
        }
    });
}

#pragma mark - btn click events
- (void)startRecord
{
    [[NSNotificationCenter defaultCenter] postNotificationName:kMusicShouldStopNotification object:nil];
    
    [self.microphone startFetchingAudio];
    
    self.startBtn.hidden = YES;
    self.stopBtn.hidden = NO;
    self.barAnimationView.hidden = NO;
}

- (void)stopRecord
{
    [self.microphone stopFetchingAudio];
    
    self.startBtn.hidden = NO;
    self.stopBtn.hidden = YES;
    self.barAnimationView.hidden = YES;
}

@end
